//index.vue
<template>
	<div>
		<vue-tinymce :key="tinymceFlag" v-model="Editortext" :setting="setting" @change="change" :setup="setting.setup" />
	</div>
</template>
<script>
import { UploadGetToken, uploadImage, uploadVideo } from '@/api/upload'; //上传图片的接口
import defaultSettings from '@/settings';
import * as qiniu from 'qiniu-js';
export default {
	name: 'tinymce',
	props: {
		height: {
			type: [Number, String],
			required: false,
			default: 320
		},
		width: {
			type: [Number, String],
			required: false,
			default: 'auto'
		},
		content: {
			//父组件传进来的默认值
			type: String,
			default: ''
		},
		custom: {
			//添加自定义菜单按钮
			type: String,
			default: ''
		},
		//菜单参数
		settingData: {
			type: Object,
			default() {
				return {

				}
			}
		},
		onMessage: Function
	},
	activated() {
		this.tinymceFlag++ //组件缓存的时候用于再次加载，不然有些时候再次加载会出现只显示一个textarea的问题
	},
	data() {
		let _this = this
		return {
			tinymceFlag: 1,
			Editortext: this.content,
			setting: {
				menubar: this.settingData.menubar, //上面的菜单隐藏
				selector: `#Editor${_this.itemkey}`, //多个富文本的时候加上itemkey用于区分
				toolbar: this.settingData.toolbar,
				plugins: this.settingData.plugins,
				language: this.$store.getters.languageId === 1 ? 'zh_CN' : 'en_US', //本地化设置
				tp_i18n_langs: true,
				paste_data_images: this.settingData.paste_data_images, // 默认是false的，记得要改为true才能粘贴
				images_file_types: this.settingData.images_file_types, //images_file_types允许拖入的图片后缀, 如果设置会提示拖入文件不支持
				statusbar: false, //隐藏最底部的状态栏
				height: this.height, //默认高度
				width: this.width, //默认宽度
				image_advtab: true,
				style_formats_merge: true,
				fontsize_formats: '12px 14px 16px 18px 20px 24px 26px 28px 30px 32px 34px 36px 38px',
				font_formats:
					"宋体='宋体';仿宋='仿宋';楷体='楷体';;隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
				line_height_formats: '1 1.2 1.5 2 2.5',
				content_style:
					'body { font-family:Arial,sans-serif; font-size:14px;line-height:2 }',
				style_formats: [
					{
						title: this.$store.getters.languageId === 1 ? '首行缩进' : 'text-indent',
						block: 'p',
						styles: { 'text-indent': '2em' }
					}
				],
				setup: function (editor) {
					editor.on('input blur undo redo execCommand paste', () => {
						//多个触发事件获取最新值a
						var msg = _this.Editortext.toString() //获取带html的值
						if (_this.onMessage) {
							_this.onMessage(msg)
						}
					})
				},
				// 图片异步上传处理函数
				images_upload_handler: (blobInfo, success, failure) => {
					this.handleImageAdded(blobInfo, success, failure)
				},
				file_picker_callback: (callback, value, meta) => {
					var filetype = ''
					if (meta.filetype === 'media') {
						filetype = ' .mp3, .mp4, .video, .audio,'
					} else if (meta.filetype === 'image') {
						filetype = '.jpg, .png, .jpeg, .gif'
					}
					let inputElem = document.createElement('input') //创建文件选择
					inputElem.setAttribute('type', 'file')
					inputElem.setAttribute('accept', filetype)
					inputElem.click()
					inputElem.onchange = () => {
						let upurl = ''
						let file = inputElem.files[0] //获取文件信息
						if (file.type.slice(0, 5) == 'video') {
							//判断文件类型  vedio
							upurl = uploadVideo
						} else {
							// 图片
							upurl = uploadImage
						}
						if (
							file.type.slice(0, 5) == 'image' &&
							file.size / 1024 / 1024 > 5
						) {
							_this.$message({
								message: this.$t('text.isFileSize') + '5M' + ',' + this.$t('placeholderTip.reSelect'),
								type: 'warning'
							})
						} else if (
							file.type.slice(0, 5) == 'video' &&
							file.size / 1024 / 1024 > 500
						) {
							_this.$message({
								message: this.$t('text.isFileSize') + '500M' + ',' + this.$t('placeholderTip.reSelect'),
								type: 'warning'
							})
							return false
						} else if (file.size / 1024 / 1024 > 5) {
							_this.$message({
								message: this.$t('text.isFileSize') + '5M' + ',' + this.$t('placeholderTip.reSelect'),
								type: 'warning'
							})
							return false
						} else {

							const loading = this.$loading({
								lock: true,
								text: this.$t('text.loading'),
								spinner: 'el-icon-loading',
								background: 'rgba(0, 0, 0, 0.5)'
							})
							var _this = this
							UploadGetToken().then(res => {
								if (res.code === 200) {
									var token = res.data.token
									// 上传时的配置
									var config = {
										useCdnDomain: true
									}
									//  设置文件的配置
									var putExtra = {
										fname: '',
										params: {},
										mimeType: null
									}
									var key = new Date().getTime()
									//   实例化七牛云的上传实例
									var observable = qiniu.upload(file, key, token, putExtra, config)
									//   设置实例的监听对象
									var observer = {
										next(res) {
											// console.log(res)
										},
										// 接收上传错误信息
										error(err) {
											console.log(err, 'err')
											_this.$message({
												message: this.$t('text.isFileFail'),
												type: 'error'
											})
											loading.close()
										},
										// 接收上传完成后的信息
										complete(res) {
											if (res.key) {
												let url = defaultSettings.BASE_IMG + res.key
												callback(url) //回显url
												loading.close()
											}
										}
									}
									// 上传开始
									var subscription = observable.subscribe(observer)
								}
							})
							// upurl({ file }).then(response => {
							// 	if (response.data.code == 200) {
							// 		loading.close()
							// 		let url = defaultSettings.BASE_IMG + response.data.data
							// 		callback(url) //回显url
							// 	}
							// })
						}
					}
				}
			}
		}
	},
	watch: {
		content: {
			immediate: true,
			deep: true,
			handler() {
				// 这里是从列表页编辑时做的内容注入，没有需要可以不写
				if (this.content == undefined) {
					this.Editortext = ''
				} else {
					this.Editortext = this.content
				}
			}
		}
	},

	methods: {
		// 插入图片的方法
		handleImageAdded(blobInfo, success, failure) {
			let file = blobInfo.blob()
			var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
			const extension = testmsg === 'png'
			const extension2 = testmsg === 'jpg'
			const extension3 = testmsg === 'jpeg'
			const extension4 = testmsg === 'gif'
			const isLt5M = file.size / 1024 / 1024 < 5
			if (!extension && !extension2 && !extension3 && !extension4) {
				_this.$message({
					message: this.$t('text.isFormat'),
					type: 'warning'
				})
				return false
			}
			if (!isLt5M) {
				_this.$message({
					message: this.$t('text.isFileSize') + '5M' + ',' + this.$t('placeholderTip.reSelect'),
					type: 'warning'
				})
				return false
			}
			const loading = this.$loading({
				lock: true,
				text: this.$t('text.loading'),
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.5)'
			})
			var _this = this
			UploadGetToken().then(res => {
				if (res.code === 200) {
					var token = res.data.token
					// 上传时的配置
					var config = {
						useCdnDomain: true
					}
					//  设置文件的配置
					var putExtra = {
						fname: '',
						params: {},
						mimeType: null
					}
					var key = new Date().getTime()
					//   实例化七牛云的上传实例
					var observable = qiniu.upload(file, key, token, putExtra, config)
					//   设置实例的监听对象
					var observer = {
						next(res) {
							// console.log(res)
						},
						// 接收上传错误信息
						error(err) {
							console.log(err, 'err')
							_this.$message({
								message: this.$t('text.isFileFail'),
								type: 'error'
							})
							loading.close()
						},
						// 接收上传完成后的信息
						complete(res) {
							if (res.key) {
								let url = defaultSettings.BASE_IMG + res.key
								success(url) //回显url
								loading.close()
								return
							}
						}
					}
					// 上传开始
					var subscription = observable.subscribe(observer)
				}
			})
			// loading.close()
			// 原上传图片
			// const loading = this.$loading({
			// 	lock: true,
			// 	text: this.$t('text.loading'),
			// 	spinner: 'el-icon-loading',
			// 	background: 'rgba(0, 0, 0, 0.5)'
			// })
			// const formdate = new FormData()
			// formdate.set('file', blobInfo.blob())
			// uploadImage({ file }).then(response => {
			// 	if (response.data.code == 200) {
			// 		let url = defaultSettings.BASE_IMG + response.data.data
			// 		success(url) //回显url
			// 		loading.close()
			// 		return
			// 	}
			// }).catch(err => {
			// 	loading.close()
			// 	console.log(err);
			// });
		},
		change() {
			//这里只有输入框改变的时候才会触发，比如自定义模板选择的时候就触发不了
		}
	}
}
</script>
<style lang="scss">
.tox-dialog__body-nav> :nth-child(2) {
	display: none !important;
}
</style>
